package io.rasterizing;

import graphics.SimpleModel;
import graphics.rasterizing.model.Model;
import graphics.rasterizing.model.Triangle;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 
 */
public class SimpleReader implements ModelReader {
	private Scanner _file;
	private Map<Integer, float[]> _vertices = new HashMap<Integer, float[]>();
	private Collection<int[]> faces = new ArrayList<int[]>();
	private int _vertexCount;

	public SimpleReader(String file) throws FileNotFoundException {
		_file = new Scanner(new File(file));
		_vertexCount = 1;
	}

	@Override
	public Model read() {
		SimpleModel model = new SimpleModel();
		while (_file.hasNext()) {
			handleString(_file.nextLine());
		}
		for (int[] face : faces) {
			model.add(genTriangle(face));
		}
		return model;
	}

	private Triangle genTriangle(int[] face) {
		float[][] value = new float[3][];
		for (int i = 0; i < value.length; i++)
			value[i] = _vertices.get(face[i]);
		float[][] color = new float[3][];
		float[] randomc = randomcolor();
		for (int i = 0; i < color.length; i++) {
			randomc = new float[3];
			for (int j = 0; j < randomc.length; j++)
				randomc[j] = 1;

			color[i] = randomc;
		}
		return new Triangle(value, color);
	}

	private float[] randomcolor() {

		return null;
	}

	private void handleString(String line) {
		if (line.matches("v .*"))
			handleVertex(line);
		if (line.matches("f [0-9]*/[0-9]*/[0-9]*/ [0-9]*/[0-9]*/[0-9]*/[0-9]*/[0-9]*/[0-9]*/")) // simple
			handleFace(line);																					// face
		if (line.matches("f .*"))
			handleFace(line);
		if (line.matches("vn .*"))
			handleVertexNormal(line);
		if (line.matches("vt "))
			;//

		// donothing
	}

	private void handleVertexNormal(String line) {
		// ignore vertex normals for now
	}

	private void handleFace(String line) {
		Scanner s = new Scanner(line);
		s.skip("f ");
		String t = s.next("([0-9])*(/)([0-9])*(/)([0-9])*");
		int a = new Integer(t.split("(/)")[0]);
		t = s.next("([0-9])*(/)([0-9])*(/)([0-9])*");
		int b = new Integer(t.split("(/)")[0]);
		t = s.next("([0-9])*(/)([0-9])*(/)([0-9])*");
		int c = new Integer(t.split("(/)")[0]);
		int[] r = new int[3];
		r[0] = a;
		r[1] = b;
		r[2] = c;
		faces.add(r);
	}

	private void handleVertex(String line) {
		Scanner s = new Scanner(line);
		s.skip("v ");
		float x = new Float(s.next("([0-9]|.|-)*"));
		float y = new Float(s.next("([0-9]|.|-)*"));
		float z = new Float(s.next("([0-9]|.|-)*"));
		_vertices.put(_vertexCount++, ar(x, y, z, 1));
	}

	public static float[] ar(float... floats) {
		return floats;
	}
}
